package com.h3bpm.kumhosunny.crm.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.DataModel.BizObjectSchema;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.WorkflowTemplate.WorkflowDocument.PublishedWorkflowTemplateHeader;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.h3bpm.base.res.ResBody;
import com.h3bpm.kumhosunny.common.H3Property;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import com.h3bpm.kumhosunny.knowledge.enums.Knowledge;
import data.DataRow;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhengyj
 * @date 2019/9/10
 * @description 出差类流程控制器
 */
@Controller
@RequestMapping("/Portal/CRM/Travel")
public class TravelController extends ControllerBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBase.class);

    private static final String BUSINESSOPPORTUNITY = "businessOpportunity";

    @Override
    public String getFunctionCode() {
        return null;
    }

    private BPMService bpmService = new BPMServiceImpl();

    /****
     * 功能描述: 根据出差报告创建商机
     *
     * @Param: [instanceId]
     * @Return: com.h3bpm.base.res.ResBody
     * @Author: zhengyj
     * @Date: 2019/9/10 14:09
     */
    @RequestMapping(
            value = {"/createOpportunityByTravelReport"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public ResBody createOpportunityByTravelReport(String instanceId) {
        LOGGER.warn("==========根据出差报告创建商机===========instanceId：" + instanceId);
        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();

           DataTable customerTable = SqlUtil.doQuery("select sheetYype,trade from i_CustomerProfile where customerCode = '"+valueTable.get("customerCode").toString()+"'");

            BizObject[]  bizObjects= (BizObject[]) valueTable.get("SJXSList");
           if(bizObjects!=null && bizObjects.length>0) {
               for (BizObject bizObject : bizObjects) {
                   Map<String, Object> zbValueTable = bizObject.getValueTable();
                   if (zbValueTable.get("SXType") != null) {
                       String SXType = zbValueTable.get("SXType").toString();
                       if ("商机".equals(SXType)) {
                           List<DataItemParam> createParams = new ArrayList<>();
                           String source = "出差报告";
                           createParams.add(new DataItemParam("createPerson", valueTable.get("createPerson").toString()));
                           createParams.add(new DataItemParam("source", source));
                           createParams.add(new DataItemParam("customerName", valueTable.get("customerName").toString()));
                           createParams.add(new DataItemParam("customerCode", valueTable.get("customerCode").toString()));
                           createParams.add(new DataItemParam("customerContact", valueTable.get("customerContact").toString()));
                           if(zbValueTable.get("JHMC")!=null) {
                               createParams.add(new DataItemParam("businessOpportunityName", zbValueTable.get("JHMC").toString()));
                           }
                           createParams.add(new DataItemParam("describeRemark", valueTable.get("describeRemark").toString()));
                           createParams.add(new DataItemParam("ccPerson", zbValueTable.get("ccPerson")));
                           if (customerTable != null && customerTable.getEntityRows() != null && customerTable.getEntityRows().size() > 0) {
                               createParams.add(new DataItemParam("industry", customerTable.getEntityRows().get(0).getString("sheetYype")));
                               createParams.add(new DataItemParam("subIndustry", customerTable.getEntityRows().get(0).getString("trade")));
                           }
                           if (zbValueTable.get("LBJ") != null) {
                               createParams.add(new DataItemParam("partname", zbValueTable.get("LBJ").toString()));
                           }
                           if (zbValueTable.get("xyl") != null) {
                               createParams.add(new DataItemParam("backing", zbValueTable.get("xyl").toString()));
                           }
                           if (zbValueTable.get("affair") != null) {
                               createParams.add(new DataItemParam("businessDescription", zbValueTable.get("affair").toString()));
                           }
                           createParams.add(new DataItemParam("travelReportInstanceId", instanceId));
                           LOGGER.info("====== 根据出差报告发起商机流程=========发起人:" + valueTable.get("createPerson").toString());
                           BPMServiceResult bpmServiceResult = bpmService.StartWorkflow(H3Property.SYSTEMCODE, H3Property.SECRET, "businessOpportunity", user.getCode(), false, createParams);
                           if (bpmServiceResult.isSuccess()) {
                               LOGGER.info("==========根据出差报告发起商机流程=========== success");
                           } else {
                               LOGGER.info("==========根据出差报告发起商机流程=========== filed");
                           }
                       } else if ("线索".equals(SXType)) {
                           List<DataItemParam> createParams = new ArrayList<>();
                           createParams.add(new DataItemParam("discoverer", user.getObjectID()));
                           createParams.add(new DataItemParam("customername", valueTable.get("customerName").toString()));
                           createParams.add(new DataItemParam("customerCode", valueTable.get("customerCode").toString()));
                           if(zbValueTable.get("JHMC")!=null) {
                               createParams.add(new DataItemParam("BOLname", zbValueTable.get("JHMC").toString()));
                           }
                           createParams.add(new DataItemParam("describeRemark", valueTable.get("describeRemark").toString()));
                           createParams.add(new DataItemParam("copyto", zbValueTable.get("ccPerson")));
                           if (customerTable != null && customerTable.getEntityRows() != null && customerTable.getEntityRows().size() > 0) {
                               createParams.add(new DataItemParam("lineindustry", customerTable.getEntityRows().get(0).getString("sheetYype")));

                               createParams.add(new DataItemParam("lineindustry2", customerTable.getEntityRows().get(0).getString("trade")));
                           }
                           if (zbValueTable.get("LBJ") != null) {
                               createParams.add(new DataItemParam("department", zbValueTable.get("LBJ").toString()));
                           }
                           if (zbValueTable.get("xyl") != null) {
                               createParams.add(new DataItemParam("backing", zbValueTable.get("xyl").toString()));
                           }
                           if (zbValueTable.get("affair") != null) {
                               createParams.add(new DataItemParam("demendofdescription", zbValueTable.get("affair").toString()));
                           }
                           createParams.add(new DataItemParam("travelReportInstanceId", instanceId));
                           LOGGER.info("====== 根据出差报告发起线索流程=========发起人:" + valueTable.get("createPerson").toString());
                           BPMServiceResult bpmServiceResult = bpmService.StartWorkflow(H3Property.SYSTEMCODE, H3Property.SECRET, "Businessopportunitylead", user.getCode(), false, createParams);
                           if (bpmServiceResult.isSuccess()) {
                               LOGGER.info("==========根据出差报告发起商机流程=========== success");
                           } else {
                               LOGGER.info("==========根据出差报告发起商机流程=========== filed");
                           }

                       }

                   }
               }
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResBody.buildSuccessResBody();
    }


    /****
     * 功能描述: 根据出差申请发起出差报告流程
     *
     * @Param: [instanceId]
     * @Return: com.h3bpm.base.res.ResBody
     * @Author: zhengyj
     * @Date: 2019/9/10 14:44
     */
    @RequestMapping(
            value = {"/createTravelReportByTravelAppl"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public ResBody createTravelReportByTravelAppl(String instanceId) {
        LOGGER.warn("==========根据出差申请发起出差报告流程===========instanceId：" + instanceId);
        ResBody result = ResBody.buildFailResBody();
        try {
            //根据流程id获取创建人
            String querySql = "SELECT b.`Name` FROM (SELECT Originator FROM ot_instancecontext   WHERE ObjectId='" + instanceId + "') s LEFT JOIN ot_user b ON s.Originator = b.ObjectID";
            DataTable dataTable = SqlUtil.doQuery(querySql);
            List<DataRow> entityRows = dataTable.getEntityRows();
            String name = null;
            if (entityRows.isEmpty()) {
            } else {
                DataRow dataRow = entityRows.get(0);
                name = dataRow.getString(0);
            }
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
            // 处理子表
            BizObject[] detailTable = (BizObject[]) valueTable.get("travelPlanDeatil");
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getBizObject().getOwnerId());
            if (null != detailTable) {
                for (BizObject detail : detailTable) {
                    HashMap<String, Object> detailValueTable = detail.getValueTable();
                    List<DataItemParam> createParams = new ArrayList<>();
                    createParams.add(new DataItemParam("createPerson", name));
                    createParams.add(new DataItemParam("customerName", detailValueTable.get("customerName").toString()));
                    createParams.add(new DataItemParam("customerCode", detailValueTable.get("customerCode").toString()));
                    createParams.add(new DataItemParam("customerContact", detailValueTable.get("customerContact").toString()));
                    createParams.add(new DataItemParam("travelGoal", detailValueTable.get("travelGoal").toString()));
                    createParams.add(new DataItemParam("event", detailValueTable.get("event").toString()));
                    createParams.add(new DataItemParam("travelApplInstanceId", instanceId));
                    LOGGER.info("====== 根据出差发起出差报告流程=========发起人:" + user.getName());
                    BPMServiceResult bpmServiceResult = bpmService.StartWorkflow(H3Property.SYSTEMCODE, H3Property.SECRET, "businesstravelreport", user.getCode(), false, createParams);
                    if (bpmServiceResult.isSuccess()) {
                        LOGGER.info("==========根据出差申请发起出差报告流程=========== success");
                    } else {
                        LOGGER.info("==========根据出差申请发起出差报告流程=========== filed");
                    }
                }

            }

        } catch (Exception e) {
            result.setErrorMsg(e.getMessage());
            e.printStackTrace();
            return result;
        }
        return ResBody.buildSuccessResBody();
    }

    /****
     * 功能描述: 回写出差申请判定
     *
     * @Param: [instanceId]
     * @Return:
     * @Author: wjq
     * @Date: 2019/11/2 14:09
     */
    @RequestMapping(
            value = {"/updateStates"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public ResBody testPicture(String instanceId) {
        LOGGER.warn("==========根据出差报告回写出差申请===========instanceId：" + instanceId);
        ResBody result = ResBody.buildFailResBody();
        String sql = "SELECT o.state,o.ObjectId FROM ot_instancecontext o,i_businessTravelReport b " +
                "WHERE   b.ObjectId=o.bizObjectId AND b.travelApplInstanceId in " +
                "(SELECT t.travelApplInstanceId FROM ot_instancecontext o,i_businessTravelReport t " +
                "WHERE o.ObjectId='" + instanceId + "' AND t.ObjectId=o.bizObjectId)";
        try {
            String no = "2";
            String  state ="";
            DataTable dataTable = SqlUtil.doQuery(sql);
            List<DataRow> entityRows = dataTable.getEntityRows();
            if (dataTable.getRows()!= null && dataTable.getRows().size() > 0) {
                for( DataRow dataRow :  dataTable.getEntityRows()) {
                    //对里面的每个报告单进行判断
                     String objectId = dataRow.getString("ObjectId");
                     state = dataRow.getString("state");
                     //排除本流程
                     if (instanceId.equals(objectId)||instanceId==objectId){
                     }else {
                         if (state.equals(no) || state == no) {
                             return ResBody.buildSuccessResBody("报告单未结束");
                         }
                     }
                }
            }
            //更改数据库出差申请状态
            //trans(instanceId);
            String sql2 ="UPDATE i_travelappl SET states='完成' WHERE ObjectId=(SELECT bizObjectId FROM ot_instancecontext WHERE ObjectId in " +
                    "(SELECT t.travelApplInstanceId FROM ot_instancecontext o,i_businessTravelReport t  " +
                    "WHERE o.ObjectId='" + instanceId + "' AND t.ObjectId=o.bizObjectId))";
            SqlUtil.doNoQuery(sql2);
        } catch (Exception e) {
            result.setErrorMsg(e.getMessage());
            e.printStackTrace();
            return result;
        }
        return ResBody.buildSuccessResBody();
    }
    public  void  trans(String instanceId ){
        String sql2 ="UPDATE i_travelappl SET states='完成' WHERE ObjectId=(SELECT bizObjectId FROM ot_instancecontext WHERE ObjectId in " +
                "(SELECT t.travelApplInstanceId FROM ot_instancecontext o,i_businessTravelReport t  " +
                "WHERE o.ObjectId='" + instanceId + "' AND t.ObjectId=o.bizObjectId))";
        try {
        SqlUtil.doQuery(sql2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
